package org.chen.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.chen.common.exception.ServiceException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    /**
     * 配置Feign的日志级别
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    /**
     * 请求拦截器，添加请求头等信息
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            requestTemplate.header("Content-Type", "application/json;charset=UTF-8");
            // 可以在这里添加认证信息等
            requestTemplate.header("Internal-Call", "true");
        };
    }

    /**
     * 错误解码器，处理服务调用异常
     */
    @Bean
    public ErrorDecoder errorDecoder() {
        return new FeignErrorDecoder();
    }

    /**
     * 自定义错误解码器
     */
    public class FeignErrorDecoder implements ErrorDecoder {
        private final ErrorDecoder defaultErrorDecoder = new Default();

        @Override
        public Exception decode(String methodKey, Response response) {
            if (response.status() >= 400 && response.status() <= 499) {
                return new ServiceException("客户端请求错误");
            }
            if (response.status() >= 500 && response.status() <= 599) {
                return new ServiceException("服务端错误");
            }
            return defaultErrorDecoder.decode(methodKey, response);
        }
    }
}